// SPDX-License-Identifier: GPL-2.0 or GPL-3.0
// Copyright © 2018-2019 Ariadne Devos
/* sHT -- file descriptor manipulation (Unix) */

/* The worker can requests the control thread to send back a passive socket.
   Alternatively, the worker can allocate it by itself if it has appropriate
   priviles or if it is a control thread itself. This code is for the
   latter case.

   Support:

   IPv6, IPv4: TCP, UDP
   Unix: /
 */

#ifndef _sHT_SOCKET_H
#define _sHT_SOCKET_H

#include <fcntl.h>
#include <netinet/in.h>
#include <stdint.h>
#include <sys/socket.h>

/* TODO This usage of O_NONBLOCK is Linux-specific. */
enum sHT_sock_type
{
	sHT_SOCK_STREAM = SOCK_STREAM | O_NONBLOCK,
	sHT_SOCK_STREAM_CLOEXEC = SOCK_STREAM | O_NONBLOCK | O_CLOEXEC,
	sHT_SOCK_DGRAM = SOCK_DGRAM | O_NONBLOCK,
	sHT_SOCK_DGRAM_CLOEXEC = SOCK_DGRAM | O_NONBLOCK | O_CLOEXEC,
};

/* IPv4 is a subset of IPv6 (via V4-mapped addresses), sort of. */
struct sHT_passive_in6
{
	struct sockaddr_in6 addr;
	enum sHT_sock_type type;
	int backlog;
	/* Autocorking is not enabled by default */
	/* TODO: allow TCP_DEFER_ACCEPT (OK for HTTP, TLS?) */
};

/* Close a file descriptor. */
void
sHT_close(int fd);

/* Return a fresh IPv6 listening socket, binded to a particular address.
   It is O_NONBLOCK. Whether it is O_CLOEXEC depends upon ->type.

   The network interface does not have to be up (IP_FREEBIND).
   Ports may be reused (SO_REUSEPORT).
   TODO: binding to a particular interface (SO_BINDTODEVICE).

   In case of an error, return a negative errno value. */
__attribute__((warn_unused_result))
__attribute__((nonnull (1)))
int
sHT_passive_ipv6(const struct sHT_passive_in6 *in);

#endif
